package com.njy.consumer.controller;


import com.njy.consumer.ribbon.RibbonRule;
import com.njy.pojo.CommonResult;
import com.njy.pojo.Payment;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.net.URI;
import java.util.List;

@RestController
@Log4j2
public class ConsumerController {
    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private DiscoveryClient discoveryClient;

    @Autowired
    private RibbonRule ribbonRule;

    private final static  String PAYMENT_URL= "http://cloud-provider-payment";


    @GetMapping("/consumer/payment/get/{id}")
    public CommonResult<Payment> getPaymentById(@PathVariable(value = "id")Long id){
        return restTemplate.getForObject(PAYMENT_URL+"/payment/get/"+id,CommonResult.class);
    }

    @GetMapping("/consumer/payment/getByMyRule/{id}")
    public CommonResult<Payment> getByMyRule(@PathVariable(value = "id")Long id){

        List<ServiceInstance> instances = discoveryClient.getInstances("cloud-provider-payment");
        System.out.println(instances.size());
        ServiceInstance serviceInstance = ribbonRule.getServiceInstance(instances);
        URI uri = serviceInstance.getUri();

        return restTemplate.getForObject(uri+"/payment/get/"+id,CommonResult.class);
    }
}
